// 创建节点/边
<template>
  <el-button @click="graphAddRect" type="primary" style="margin: 10px"
    >添加矩形</el-button
  >
  <el-button @click="graphAddCircle" type="primary" style="margin: 10px"
    >添加圆</el-button
  >
  <el-button @click="graphAddEdge" type="primary" style="margin: 10px">添加边</el-button>
  <div id="container"></div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { Graph, DataUri,Shape } from "@antv/x6";
import { onMounted, ref } from "vue";

let graph = null;

const rect = new Shape.Rect({
  id: "customNode1",
  x: 40,
  y: 40,
  width: 100,
  height: 40,
  label: "rect",
  zIndex: 2,
});

const graphAddRect = () => {
  ElMessage({
    message: "添加矩形",
    type: "success",
  });

  graph.addNode(rect);
};

const circle = new Shape.Circle({
  id: "customNode3",
  x: 280,
  y: 200,
  width: 60,
  height: 60,
  label: "circle",
  zIndex: 2,
});

const graphAddCircle = () => {
  ElMessage({
    message: "添加圆",
    type: "success",
  });

  graph.addNode(circle);
};

const edge = new Shape.Edge({
  id: "edge1",
  source: rect,
  target: circle,
  zIndex: 1,
});
const graphAddEdge = () => {
  ElMessage({
    message: "添加边",
    type: "success",
  });

  graph.addEdge(edge);
};

const renderGraph = () => {
  graph = new Graph({
    container: document.getElementById("container"),
    width: 800,
    height: 600,
    panning: true,
    mousewheel: true,
    // 设置画布背景颜色
    background: {
      color: "#F2F7FA",
    },
  });

  //创建流程图数据
  const data = {
    //节点数据
    nodes: [
      {
        id: "node1",
        shape: "rect",
        x: 40,
        y: 40,
        width: 100,
        height: 40,
        label: "hello",
        attrs: {
          body: {
            stroke: "#8f8f8f",
            strokeWidth: 1,
            fill: "#fff",
            rx: 6,
            ry: 6,
          },
        },
      },
      {
        id: "node2",
        shape: "rect",
        x: 160,
        y: 180,
        width: 100,
        height: 40,
        label: "world",
        attrs: {
          body: {
            stroke: "#8f8f8f",
            strokeWidth: 1,
            fill: "#fff",
            rx: 6,
            ry: 6,
          },
        },
      },
    ],
    //边数据
    edges: [
      {
        shape: "edge",
        source: "node1", //起始点
        target: "node2", //目标点
        label: "x6",
        attrs: {
          line: {
            stroke: "#8f8f8f",
            strokeWidth: 1,
          },
        },
      },
    ],
  };

  graph.fromJSON(data); // 渲染元素
  graph.centerContent(); // 居中显示
};

onMounted(() => {
  renderGraph();
});
</script>
